import { promises as fs } from 'fs'
import { join } from 'path'

import { Command } from 'clipanion'
// @ts-expect-error
import extract from 'extract-comments'
import { fdir } from 'fdir'

const { rootDir } = require('../webpack/consts')

export class GenerateLicenseCommand extends Command {
  static paths = [['generate-license-file']]

  async execute() {
    const api = new fdir().withFullPaths().crawl(join(rootDir, 'dist'))
    const files = (await api.withPromise()) as string[]
    const licenses = files.filter((idl) => idl.endsWith('.LICENSE.txt'))
    const licensesContent = await Promise.all(licenses.map((p) => fs.readFile(p, 'utf8')))
    const licenseContent = extract(licensesContent.join('\n'))
      .map(({ value }: any) => value)
      .join('\n')
      .split('\n')
      // a little bug from extract function
      .filter((line: string) => line.trim() !== '!')
      .map((line: string) => line.replace(/!/g, '').trim())
      .join('\n')
    await fs.writeFile(join(rootDir, 'packages/platform/src/modules/license/license.txt'), licenseContent)
  }
}
